<template>
  <!-- 学科 -->
  <div class="container">
    <el-card class="box-card">
      <el-row>
        <!-- 搜索 -->
        <el-col :span="21">
          <!--搜索区域 -->
          <search-keyword
            :options="searchOptions"
            :queryInfo="queryInfo"
            @search="loadSubjectsList"
          />
        </el-col>
        <el-col :span="3" style="text-align: right;">
          <!-- 新增按钮 -->
          <el-button @click="addSubClick" type="success" icon="el-icon-edit" size="small">新增学科</el-button>
        </el-col>
      </el-row>

      <!-- 消息提示文案 -->
      <el-alert :title="`数据一共${total}条`" :closable="false" type="info" show-icon></el-alert>

      <!-- 表格 -->
      <el-table :data="subjectsList" style="width: 100%" stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="subjectName" label="学科名称" width="110px"></el-table-column>
        <el-table-column prop="username" label="创建者" width="110px"></el-table-column>
        <el-table-column label="创建日期" width="160px">
          <template slot-scope="scope">{{scope.row.addDate | formatDate}}</template>
        </el-table-column>
        <el-table-column label="前台是否显示" width="110px">
          <template slot-scope="scope">{{scope.row.isFrontDisplay?'是':'否'}}</template>
        </el-table-column>
        <el-table-column prop="twoLevelDirectory" label="二级目录"></el-table-column>
        <el-table-column prop="tags" label="标签"></el-table-column>
        <el-table-column prop="totals" label="题目数量"></el-table-column>
        <el-table-column label="操作" width="240px">
          <template slot-scope="scope">
            <!-- 带参数的编程式导航 -->
            <el-link
              :underline="false"
              type="primary"
              @click="$router.push({path: '/subjects/directorys', query: {id: scope.row.id, name: scope.row.subjectName}})"
            >学科分类</el-link>
            <el-link
              :underline="false"
              type="primary"
              @click="$router.push({path: '/subjects/tags', query: {id: scope.row.id, name: scope.row.subjectName}})"
            >学科标签</el-link>
            <el-link :underline="false" type="primary" @click="editSub(scope.row)">修改</el-link>
            <el-link :underline="false" type="primary" @click="deleteSub(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        class="pagenation"
        :queryInfo="queryInfo"
        :total="total"
        @pagination="loadSubjectsList"
      />
    </el-card>

    <!-- 新增学科 / 修改学科 对话框 -->
    <el-dialog
      @close="editSubClose"
      :title="editTitle"
      :visible.sync="editSubDialogVisible"
      width="40%"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px">
        <el-form-item label="活动名称：" prop="subjectName">
          <el-input v-model="editForm.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示：">
          <el-switch
            v-model="editForm.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEditSub">取 消</el-button>
        <el-button type="primary" @click="editSubHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SearchKeyword from '@/components/SearchKeyword'
import Pagination from '@/components/Pagination'
import { list as getSubjectsList, add as addSubject, update as updateSubject, detail as getSubById, remove as removeSubById } from '@/api/hmmm/subjects'
import { list as getDirectorys, remove as removeDirectorys } from '@/api/hmmm/directorys'
import { list as getTags, remove as removeTags } from '@/api/hmmm/tags'

export default {
  name: 'Subjects',
  data() {
    return {
      // 搜索框配置项
      searchOptions: {
        placeholder: '根据学科名搜索', // 输入框内提示信息
        sapntext1: '学科名称' // label提示1
      },
      // 学科数据对象
      subjectsList: [],
      // 学科列表请求参数对象
      queryInfo: {
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      // 总学科数
      total: 0,
      // 新增学科对话框的显示
      editSubDialogVisible: false,
      // 新增/修改对话框标题
      editTitle: '',
      // 新增学科 / 修改学科的表单对象
      editForm: {
        subjectName: '',
        isFrontDisplay: true,
        // 当前学科Id
        id: null
      },
      // 新增表单的验证规则对象
      editFormRules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 获取学科列表
    async loadSubjectsList() {
      try {
        const { data } = await getSubjectsList({
          page: this.queryInfo.page,
          pagesize: this.queryInfo.pagesize,
          subjectName: this.queryInfo.keyword
        })
        this.subjectsList = data.items
        this.total = data.counts
      } catch (error) {
        this.$message.erro('操作失败')
      }
    },

    // 点击新增学科按钮
    addSubClick() {
      this.editSubDialogVisible = true
      this.editTitle = '新增学科'
    },

    // 点击取消按钮（新增 / 修改学科）
    cancelEditSub() {
      // 重置表单
      this.$refs.editForm.resetFields()
      // 关闭对话框
      this.editSubDialogVisible = false
    },

    // 对话框关闭-重置表单项
    editSubClose() {
      this.editForm.subjectName = ''
      this.editForm.isFrontDisplay = true
    },

    // 点击修改按钮
    async editSub(subject) {
      // 根据id查询当前学科的信息
      try {
        const { data } = await getSubById(subject)
        // 显示对话框
        this.editSubDialogVisible = true
        this.editTitle = '修改学科'

        // 将当前学科信息展示到对话框
        this.editForm.subjectName = data.subjectName
        this.editForm.isFrontDisplay = !!data.isFrontDisplay
        this.editForm.id = data.id
      } catch (error) {
        this.$message.error('当前学科信息获取失败')
      }
    },

    // 确认新增 / 修改学科
    editSubHandle() {
      // 表单预校验
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return

        // 预校验成功，发送添加学科请求
        try {
          // 判断是新增还是修改
          if (this.editTitle === '新增学科') {
            // 新增
            const { data } = await addSubject({
              subjectName: this.editForm.subjectName,
              isFrontDisplay: this.editForm.isFrontDisplay ? 1 : 0
            })

            this.$message.success('添加学科成功')
          } else {
            // 修改
            try {
              const { data } = await updateSubject(this.editForm)
              this.$message.success('修改学科成功')
            } catch (error) {
              this.$message.error('修改学科失败，请稍后重试')
            }
          }

          // 更新视图
          this.loadSubjectsList()
          // 关闭对话框
          this.editSubDialogVisible = false
          this.editForm.subjectName = ''
          this.editForm.isFrontDisplay = true
        } catch (error) {
          this.$message.error('添加学科失败，请稍后再试')
        }
      })
    },

    // 删除学科
    async deleteSub(subject) {
      const result = await this.$confirm('此操作将永久删除该学科, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (result !== 'confirm') {
        return this.$message('您已取消了删除操作')
      }

      // 发送删除请求
      try {
        const { data } = await removeSubById(subject)
        this.$message.success('删除成功')

        // 根据删除的学科id获取它的所有目录并删除
        this.getDirectorysHandle(subject.id)

        // 根据删除的学科id获取它的所有标签并删除
        this.getDirectorysHandle(subject.id)

        // 更新视图
        this.loadSubjectsList()
      } catch (error) {
        this.$message.error('删除失败，请稍后再试')
      }
    },

    // 根据当前学科的id获取目录并删除
    async getDirectorysHandle(id) {
      try {
        const { data } = await getDirectorys({
          subjectID: id
        })
        data.items.forEach(async (directory) => {
          await removeDirectorys(directory)
        })
      } catch (error) {}
    },

    // 根据当前学科的id获取标签并删除
    async getDirectorysHandle(id) {
      try {
        const { data } = await getTags({
          subjectID: id
        })
        data.items.forEach(async (tag) => {
          await removeTags(tag)
        })
      } catch (error) {}
    }
  },
  created() {
    this.loadSubjectsList()
  },
  components: {
    SearchKeyword,
    Pagination
  }
}
</script>

<style scoped lang='scss'>
.container {
  padding: 10px;
  .el-alert,
  .el-row,
  .el-table,
  .pagenation {
    margin-bottom: 15px;
  }
  .el-link {
    margin: 0 5px;
  }
  .pagenation {
    float: right;
  }
}
</style>
